import Vue from 'vue'
import axios from 'axios'
import vueaxios from 'vue-axios'
import qs from 'qs';
import VueParticles from 'vue-particles'

import 'normalize.css/normalize.css' // A modern alternative to CSS resets

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import locale from 'element-ui/lib/locale/lang/en' // lang i18n

import '@/styles/index.scss' // global css

import App from './App'
import store from './store'
import router from './router'

import '@/icons' // icon
import '@/permission' // permission control

/**
 * If you don't want to use mock-server
 * you want to use MockJs for mock api
 * you can execute: mockXHR()
 *
 * Currently MockJs will be used in the production environment,
 * please remove it before going online ! ! !
 */
if (process.env.NODE_ENV === 'production') {
  const { mockXHR } = require('../mock')
  mockXHR()
}

// set ElementUI lang to EN
//Vue.use(ElementUI, { locale })
// 如果想要中文版 element-ui，按如下方式声明
Vue.use(ElementUI)

Vue.use(VueParticles)

Vue.use(vueaxios, axios)

Vue.config.productionTip = false

Vue.prototype.$qs = qs;

new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})

/**
 * axios全局请求拦截器,拦截所有axios请求
 * 每次发送axios请求携带Token请求头,携带访问令牌请求后端
 */
axios.interceptors.request.use(
	config => {
		if (sessionStorage.getItem('accessToken')) {
			config.headers.Authorization = 'Bearer ' + sessionStorage.getItem('accessToken');
		}
		
		return config;
	},
	error => {
		return Promise.reject(error);
	});


/**
 * axios全局响应拦截器,拦截所有axios响应
 * 每次响应判断状态码,若为401给出友好提示,并跳转到401未授权页面
 */
axios.interceptors.response.use(
	response => {
		return response;
	},
	error => {
		if(error.response.status === 401) {
			Vue.prototype.$message({
				message: '对不起,您没有当前资源的访问权限!',
				type: 'error',
				center: true
			})
			router.push({path: '/401'})
			return;
		}
		return Promise.reject(error);
	});
